package app.labs.LabServlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Servlet extends HttpServlet {
    
    private Controller controller;
    
    protected void mapping (HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String[] url = request.getRequestURI().split("/");
        int firstIndex = 3;
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            controller = new Controller (request, out);

            if (firstIndex < url.length && url[firstIndex].equals("checkPoint")) {
                response.setContentType("application/json");
                controller.checkPoint (Float.parseFloat(request.getParameter("x")), 
                        Float.parseFloat(request.getParameter("y")), Float.parseFloat(request.getParameter("r")));
            }
            else {
                response.setContentType("text/html");
                controller.getMainPage ();
            }
        }
        finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        mapping(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        mapping(request, response);
    }
}
